var express = require('express');
var router = express.Router();
var queryPromise = require('../pool/poolmysql').queryPromise;

// 获取一级菜单
router.get('/oneMenu', async (req, res, next) => {
  try {
    // 查找第一级菜单
    let sql_first = "select * from sp_category where cat_pid=?";
    let menus = await queryPromise(sql_first, [0]);
    res.json({
      status: 1,
      data: menus
    });
  } catch (error) {
    res.json({
      status: 0,
      message: "错误"
    });
  }
});

// 获取二级菜单
router.get('/twoMenu', async (req, res, next) => {
  try {
    // 查找第一级菜单
    let sql_first = "select * from sp_category where cat_pid=?";
    let menus = await queryPromise(sql_first, [0]);
    for (let i = 0; i < menus.length; i++) {
      // 查找二级菜单
      let sql_two = "select * from sp_category where cat_level=? and cat_pid=?";
      let two_level = await queryPromise(sql_two, [1, menus[i].cat_id]);
      menus[i].children = two_level;
    }
    res.json({
      status: 1,
      data: menus
    });
  } catch (error) {
    res.json({
      status: 0,
      message: "错误"
    });
  }
});
// 获取三级菜单
router.get('/threeMenu', async (req, res, next) => {
  try {
    // 查找第一级菜单
    let sql_first = "select * from sp_category where cat_pid=?";
    let menus = await queryPromise(sql_first, [0]);
    for (let i = 0; i < menus.length; i++) {
      // 查找二级菜单
      let sql_two = "select * from sp_category where cat_level=? and cat_pid=?";
      let two_level = await queryPromise(sql_two, [1, menus[i].cat_id]);
      menus[i].children = two_level;
      for (let j = 0; j < menus[i].children.length; j++) {
        // 查找三级菜单
        let three_level = await queryPromise(sql_two, [2, menus[i].children[j].cat_id]);
        menus[i].children[j].children = three_level;
      }
    }
    res.json({
      status: 1,
      data: menus
    });
  } catch (error) {
    res.json({
      status: 0,
      message: "错误"
    });
  }
});

// 获取原始数据
router.get('/originMenu', async (req, res, next) => {
  try {
    // 查找第一级菜单
    let sql_first = "select * from sp_category";
    let menus = await queryPromise(sql_first, []);
    res.json({
      status: 1,
      data: menus
    });
  } catch (error) {
    res.json({
      status: 0,
      message: "错误"
    });
  }
});

module.exports = router;